#include "client.h"
#include <QTcpSocket>
#include <QDataStream>
#include <QtNetwork>

Client::Client(QObject *parent) : QObject(parent)
{
    tcpServer = new QTcpSocket(this);
    connect(tcpServer, &QTcpSocket::readyRead, this, &Client::readMessage);
    connect(tcpServer, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError)));

    newConnect();
}

void Client::newConnect()
{
    blockSize = 0;

    tcpServer->abort();
    tcpServer->connectToHost("127.0.0.1", 6666);
}

void Client::readMessage()
{
    QDataStream in(tcpServer);
    in.setVersion(QDataStream::Qt_5_0);

    if(blockSize == 0){
        if(tcpServer->bytesAvailable() < (int) sizeof(quint16)) return;
        in>>blockSize;
    }
    if(tcpServer->bytesAvailable()<blockSize) return;
    QByteArray msg;
    in>>msg;
    qDebug()<<"msg="<<blockSize<<msg<<QString::fromUtf8(msg);
}

void Client::displayError(QAbstractSocket::SocketError)
{
    qDebug()<<tcpServer->errorString();
}
